package com.zaimokuza.cn.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zaimokuza.cn.entity.user.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * 对登录请求解析用户名密码并认证的过滤器
 *
 * @author zaimokuza
 */
@Slf4j
public class CustomizeUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        // 默认空用户名密码
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken("", "");
        // 对请求参数格式进行判断
        if (request.getContentType().contains(MediaType.APPLICATION_JSON_VALUE)) {
            // 如果是JSON格式进行解析
            ObjectMapper mapper = new ObjectMapper();
            try (InputStream is = request.getInputStream()) {
                LoginUser loginUser = mapper.readValue(is, LoginUser.class);
                authRequest = new UsernamePasswordAuthenticationToken(loginUser.getPhone(), loginUser.getPassword());
            } catch (IOException e) {
                // 出现异常打印异常信息，并传递空用户名及密码
                log.error("解析登录信息出现异常：" + e.getMessage(), e);
            }
        }
        // 往后调用
        setDetails(request, authRequest);
        return this.getAuthenticationManager().authenticate(authRequest);
    }

}
